<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        min-height: 300px;
        background-color: orange;
        color: #fff;
        font-size: 30px;
      }

      .v-enter,
      .v-leave-to {
        opacity: 0;
      }

      .v-enter-active,
      .v-leave-active {
        transition: all 1s;
      }
      .v-enter-to,
      .v-leave {
        opacity: 1;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <a href="#/a">组件a</a>
      <a href="#/b">组件b</a>
      <!-- is 输入字符串（组件的名字） 或者对象（组件配置对象） -->

      <transition mode="out-in">
        <keep-alive>
          <component :is="component"></component>
        </keep-alive>
      </transition>
    
      
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>
    <script>
      const randomComponent = (name) => ({
        name,
        template: `<div class="box" :style="{backgroundColor: color}">
            <p>组件:{{name}}</p> <p>计数{{count}}</p>
            <button @click="count++">计数++</button>
          </div>`,
        data() {
          const getRandomColor = () =>
            `rgb(${~~(Math.random() * 255)}, ${~~(Math.random() * 255)}, ${~~(
              Math.random() * 255
            )})`;
          return {
            name,
            count: 0,
            color: getRandomColor(),
            num: Math.random(),
          };
        },
      });

      // 路由表
      const route = [{
        path: '/a',    // 路径
        component:  randomComponent("ComponentA")
      },{
        path: '/b',    // 路径
        component:  randomComponent("ComponentB")
      }]

      var vm = new Vue({
        el: "#app",
        data: {
          component: randomComponent("ComponentA")
        },
        created() {
          window.addEventListener('hashchange', () => {
            console.log(window.location)

            // slice截取需要的部分/a,也就是去掉了#，原来的"#/a"
            const hash = window.location.hash.slice(1)

            // 如果hash是路径等于route中的路径，就返回那个对象,这里要保证path中的a与a标签中的a一样
            const match = route.find(item => item.path === hash)
            console.log(match)

            // 让data中的组件等于我route中获得的组件
            this.component = match.component
          })
        }
      });
    </script>
  </body>
</html>